import { View, Text, Image, ITouchEvent, Picker, RadioGroup, Radio } from '@tarojs/components'
import { useLoad } from '@tarojs/taro';
// import classNames from 'classnames';
import { useState } from 'react'
import axios from '@/request/index'

import './index.scss'

export default function News(props) {
  const { data } = props;
  const onClickExist = () => {
    props.onClickExist && props.onClickExist()
  }
  const [list, setList] = useState(data);
  const [selected, setSelected] = useState<{}>({});
  useLoad(() => {
    console.log('Page loaded.')
  })

  const onClickOption = (item, e: any) => {
    const value = e.detail.value

    if (selected[item.topic] && selected[item.topic] === value) {
      selected[item.topic] = ''
    } else {
      selected[item.topic] = value;
    }
    setSelected(selected);
    const newList = list.map(v => {
      if (v.topic === item.topic) {
        v.answers = v.answers.map((op) => {
          op.checked = (op.id == value);
          return op;
        });
      }
      return v;
    })
    setList(newList);
  }

  const onSubmit = async() => {
    const postData: any[] = [];
    list.map(v => {
      postData.push({
        ...v,
        userAnswerId: Number(selected[v.topic]),
      });
    })
    const res: any = await axios.post('/subject/userAnswer', postData)
    // debugger;
    if (res && Number(res.data.great) === list.length) {
      props.onClickSubmitSuccess && props.onClickSubmitSuccess(res.data);
    } else {
      props.onClickSubmitFail && props.onClickSubmitFail();
    }
  }

  // console.log(list, 'list');
  return (
    <View className='detail min-h-screen pb-safe-offset-6 px-4 relative'>
      <div className='flex flex-row items-center justify-end'>
        <Text className='text-[#383838] text-[36px]' onClick={onClickExist}>退出</Text>
      </div>
      {
        list.map((item, index) => {
          return (
            <View className='mb-[30px]' key={index}>
              <View>{index+1}、 {item.topic}</View>
              <View>
                
                {
                  item.answers.map((option, i) => {
                    return (
                      <View key={i}>
                        <RadioGroup onChange={(e) => onClickOption(item, e)}>
                          <Radio value={option.id} checked={option.checked}>
                            {option.answer}
                          </Radio>
                        </RadioGroup>
                      </View>
                    )
                  })
                }
              </View>
            </View>
          )
        })
      }
      <View className='fixed bottom-[44px] bg-transparent left-0 right-0 h-[64px] flex flex-row justify-center'>
        <View 
        onClick={onSubmit}
        className='bg-[#4A9BF7] rounded-[8px] w-[130px] h-[64px] text-center text-white text-[36px] leading-[64px]'>
          提交
        </View>
      </View>
    </View>
  )
}
